import axios, { AxiosResponse, AxiosRequestConfig } from 'axios'
import { errorCodeType } from './error-code-type'
import { ElMessage, ElLoading } from 'element-plus'
import { getLocal } from '@/utils/localStore'
const service = axios.create({
  baseURL: 'http://127.0.0.1:7001/',
  timeout: 2000,
  headers: {
    'Content-Type': 'application/json',
  },
})

let loading: any
let errMessage: any
interface optionsType {
  lock?: boolean
  fullScreen?: boolean
  text?: string
  background?: any
}
const options: optionsType = {
  lock: true,
  fullScreen: true,
  text: 'Loading',
  background: 'rgba(0, 0, 0, 0.7)',
}
const showLoading = () => {
  loading = ElLoading.service(options)
}
const closeLoading = () => {
  loading.close()
}

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 请求加载遮罩
    // showLoading()
    if (getLocal('token')) {
      config.headers = {
        Authorization: getLocal('token'),
      }
    }
    // 可以使用接口参数验签 请求头token等等
    return config
  },
  (error: any) => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 关闭请求遮罩
    // closeLoading()
    const res = response.data
    if (res.status == 200) {
      return res
    } else {
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  (error: any) => {
    closeLoading()
    if (error && error.response) {
      errMessage = errorCodeType(error.response.status)
    } else {
      error.message = '连接到服务器失败，请联系管理员'
    }
    ElMessage({
      message: errMessage,
      type: 'error',
    })
  }
)
export function postMethod(url: string, params = {}) {
  return service.post(url, params)
}

export function getMethod(url: string, data = {}) {
  return service.get(url, { params: data })
}
